package com.wframe.project.former.web.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.frame.common.SystemConfig;
import com.frame.database.JdataBean;
import com.frame.pageform.PageForm;
import com.frame.pageform.RequestContext;
import com.frame.util.DateConvert;
import com.frame.util.ToolUtil;
import com.frame.util.tool.image.ImageUtil;
import com.wframe.project.former.dataservices.upload.FileBean;
import com.wframe.project.former.dataservices.upload.UploadService;

/**
 * 
 * 功能:文件上传<br>
 * 参数:<br>
 * 作者:王海锋<br>
 * 时间:2017-1-13上午10:59:51<br>
 */
public class UploadPage extends PageForm{

	private JdataBean bean;
	private Logger logger=Logger.getLogger(UploadPage.class);
	
	/**
	 * 
	 * 功能:上传文件返回文件id<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2016-3-31下午02:55:29<br>
	 * @throws IOException 
	 */
	public String upload() throws IOException{
		JdataBean json=new JdataBean();
		String path=getRequest().getParameter("path");
		String dir=getRequest().getParameter("dir");
		if(RequestContext.getContext().getFileItemList()!=null){
			FileItem fileitem=RequestContext.getContext().getFileItemList().get(0);
			String fname=fileitem.getName();
			int n=fname.lastIndexOf(".");
            String type=fname.substring(n+1);
            path="/uploadfile/"+path+"/files";
            if(StringUtils.isNotBlank(dir))path+="/"+dir;
            File dirfile=new File(SystemConfig.getInstance().getRootPath()+path);
			if(!dirfile.exists())dirfile.mkdirs();
			Random rd=new Random();
			String newname=DateConvert.toString(new Date(),"yyMMddHHmmssSSS")+rd.nextInt(99)+"."+type;
			try {
				fileitem.write(new File(SystemConfig.getInstance().getRootPath()+path+"/"+newname));
				FileBean filebean=new FileBean(fname, String.valueOf(fileitem.getSize()), type, path+"/"+newname,null);
				String fileid=UploadService.getIntance().saveFile(filebean);
				json.put("error", 0);
				json.put("fileid", fileid);
				json.put("url", getRequest().getContextPath()+path+"/"+newname);
			} catch (Exception e) {
				logger.error("上传文件失败",e);
				json.put("error", 1);
				json.put("fileid", "");
				json.put("url", "");
			}
		}
//		getResponse().setContentType("text/html; charset=UTF-8");
//		getResponse().getWriter().print(getJsonObject().objToJson(json));
		return getJsonObject().JSONDATA+getJsonObject().objToJson(json);
	}
	
	/**
	 * 
	 * 功能:上传文件返回文件路径<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2016-5-27下午01:15:04<br>
	 */
	public String uploadToPath() throws IOException{
		JdataBean json=new JdataBean();
		String path=getRequest().getParameter("path");
		String dir=getRequest().getParameter("dir");
		if(RequestContext.getContext().getFileItemList()!=null){
			FileItem fileitem=RequestContext.getContext().getFileItemList().get(0);
			String fname=fileitem.getName();
			int n=fname.lastIndexOf(".");
            String type=fname.substring(n+1);
            path="/uploadfile/"+path+"/files";
            if(StringUtils.isNotBlank(dir))path+="/"+dir;
            File dirfile=new File(SystemConfig.getInstance().getRootPath()+path);
			if(!dirfile.exists())dirfile.mkdirs();
			Random rd=new Random();
			String newname=DateConvert.toString(new Date(),"yyMMddHHmmssSSS")+rd.nextInt(99)+"."+type;
			try {
				fileitem.write(new File(SystemConfig.getInstance().getRootPath()+path+"/"+newname));
				json.put("error", 0);
				json.put("url", getRequest().getContextPath()+path+"/"+newname);
			} catch (Exception e) {
				logger.error("上传文件失败",e);
				json.put("error", 1);
				json.put("fileid", "");
				json.put("url", "");
			}
		}
		return getJsonObject().JSONDATA+getJsonObject().objToJson(json);
	}
	
	/**
	 * 
	 * 功能:上传图片<br>
	 * 参数:<br>
	 * 作者:王海锋<br>
	 * 时间:2017-1-2上午01:01:39<br>
	 */
	public String uploadPhoto() throws IOException{
		JdataBean redata=new JdataBean();
		if(RequestContext.getContext().getFileItemList()!=null){
			FileItem photo=RequestContext.getContext().getFileItemList().get(0);
			String path="";
			FileInputStream filein=null;
			FileOutputStream fileout=null;
			Random random=new Random();
    		try {
    			int n=photo.getName().lastIndexOf(".");
				String type=photo.getName().substring(n+1);
    			String dir=SystemConfig.getInstance().getUploadPath();
    			if(StringUtils.isNotBlank(getRequest().getParameter("dir"))){
    				String getdir=getRequest().getParameter("dir");
    				if(!getdir.startsWith("/"))getdir="/"+getdir;
    				if(!getdir.endsWith("/"))getdir+="/";
    				dir+=getdir;
    			}else dir+="/pictures/";
    			
	        	path=UploadService.getIntance().createFileDir(dir);
    			path+=System.currentTimeMillis()+""+random.nextInt(9)+""+random.nextInt(9);
    			String viewpath=path+"_v";
    			path+="."+type;
    			viewpath+="."+type;
	    		ImageUtil imgutil= ToolUtil.getImageUtil();
	    		photo.write(new File(SystemConfig.getInstance().getRootPath()+path));
	    		if("false".equals(getRequest().getParameter("view")))viewpath="";//不生成预览
	    		else{
		    		fileout=new FileOutputStream(new File(SystemConfig.getInstance().getRootPath()+viewpath));
		    		filein=new FileInputStream(new File(SystemConfig.getInstance().getRootPath()+path));
		    		imgutil.resizeByWidth(filein, 400, fileout);
	    		}
	            JdataBean bean=new JdataBean();
	            bean.put("filename", photo.getName());
	            bean.put("filetype", type);
	            bean.put("filepath", path);
	            bean.put("createtime",new Date());
	            bean.put("viewpath", viewpath);
	            String pid="";
	            if(!"false".equals(getRequest().getParameter("tosave")))//保存到数据库
	            	pid=UploadService.getIntance().addPhoto(bean);
	            else pid=path;
	            String basePath = getRequest().getScheme()+"://"+getRequest().getServerName()+":"+getRequest().getServerPort()+getRequest().getContextPath();
	            redata.put("pid", pid);
	            redata.put("filepath", basePath+path);
	            redata.put("viewpath", basePath+viewpath);
	            redata.put("basepath", basePath);
    		} catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(fileout!=null)fileout.close();
				if(filein!=null)filein.close();
			}
    	}
		return getJsonObject().JSONDATA+getJsonObject().objToJson(redata);
	}
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
